package com.sdcqjy.property.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.sdcqjy.mylibrary.widget.PublicDialog;
import com.sdcqjy.mylibrary.widget.ShowToast;
import com.sdcqjy.mylibrary.widget.TabRadioButton;
import com.sdcqjy.property.MyConstants;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.BaseFragment;
import com.sdcqjy.property.base.BaseService;
import com.sdcqjy.property.base.SimpleBaseActivity;
import com.sdcqjy.property.home.fragment.CommentFragment;
import com.sdcqjy.property.home.fragment.HtmlFragment;
import com.sdcqjy.property.home.fragment.ImageFragment;
import com.sdcqjy.property.home.fragment.PdfFragment;
import com.sdcqjy.property.mode.AttenMode;
import com.sdcqjy.property.mode.ListMsgMode;
import com.sdcqjy.property.presenter.DetailsPresenter;
import com.sdcqjy.property.presenter.contract.DetailsContract;
import com.sdcqjy.property.utils.TitleUtils;
import com.sdcqjy.property.widget.MoreAreaShareMenu;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sdcqjy.property.MyConstants.ActionAttenRef;

/**
 * Created by 磁磁帅 on 2018/4/14.
 * 功能：
 */
public class DetailsActivity extends SimpleBaseActivity<DetailsPresenter> implements DetailsContract.View, CompoundButton.OnCheckedChangeListener {
    @BindView(R.id.textTitle)
    TextView textTitle;
    @BindView(R.id.textR)
    TextView textR;
    @BindView(R.id.radio1)
    TabRadioButton radio1;
    @BindView(R.id.radio2)
    TabRadioButton radio2;
    @BindView(R.id.layoutFrame)
    FrameLayout layoutFrame;
    @BindView(R.id.floatBtn)
    FloatingActionButton floatBtn;
    @BindView(R.id.textShar)
    View textShar;
    @BindView(R.id.layoutTitle)
    View layoutTitle;
    private ListMsgMode mode;
    private AttenMode attenMode;
    private BaseFragment oldFragment;
    private BaseFragment fragments[];
    private boolean isRun = true;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (MyConstants.ActionLogin.equals(action)) {
                handler.sendEmptyMessage(0);
                presenter.getAtten(mode.id);
                presenter.getDetailsMode(mode.id);
            }
        }
    };
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://发送已读
                    if (isRun && isLogin(false)) {
                        presenter.sendRead(mode.id);
                    }
                    break;
                case 1://获取关注信息
                    if (oldFragment != null && attenMode != null) {
                        oldFragment.sendMessage(1, attenMode);
                    }
                    break;
                case 2://关注
                    presenter.sendAtten(mode.id, 1);
                    break;
                case 3://不关注
                    presenter.sendAtten(mode.id, 0);
                    break;
                case 4://获取readNumb
                    break;
                case 5:
                    break;
            }
        }
    };

    public static void open(Context context, ListMsgMode mode) {
        Intent intent = new Intent(context, DetailsActivity.class);
        intent.putExtra("mode", mode);
        context.startActivity(intent);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        ButterKnife.bind(this);
        presenter = new DetailsPresenter(this);

        Intent intent = getIntent();
        mode = intent.getParcelableExtra("mode");

        radio1.setOnCheckedChangeListener(this);
        radio2.setOnCheckedChangeListener(this);

        IntentFilter filter = new IntentFilter(MyConstants.ActionLogin);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
    }

    protected void asynRun() {
        if (mode == null) {
            finish();
            return;
        }
        boolean gone = TitleUtils.isGone(mode.categoryID);
        if (gone) {
            findViewById(R.id.group).setVisibility(View.GONE);
            textTitle.setText(TitleUtils.getTitle(mode.categoryID));
        }

        if (TextUtils.isEmpty(mode.documentPath) || TextUtils.isEmpty(mode.documentRealName)) {
            textR.setVisibility(View.GONE);
        } else textR.setVisibility(View.VISIBLE);

        fragments = new BaseFragment[2];
        if (TextUtils.isEmpty(mode.imagePath)) {
            if (TextUtils.isEmpty(mode.htmlPath)) mode.htmlPath = MyConstants.NULL;
            if (mode.htmlPath.endsWith("pdf"))
                fragments[0] = PdfFragment.newInstance(mode).setHandler(handler);
            else fragments[0] = HtmlFragment.newInstance(mode).setHandler(handler);
        } else {
            fragments[0] = ImageFragment.newInstance(mode).setHandler(handler);
            textR.setVisibility(View.GONE);
        }
        fragments[1] = CommentFragment.newInstance(mode.id).setHandler(handler);

        radio1.setChecked(true);

        if (isLogin(false)) {
            if (!gone) presenter.getAtten(mode.id);
            if (mode.isRead == 0)
                handler.sendEmptyMessageDelayed(0, 3000);
        }
        gone = TitleUtils.canEmail(mode.categoryID);
        if (!gone) floatBtn.setVisibility(View.GONE);
        gone = TitleUtils.has关注Btn(mode.categoryID);
        if (!gone) textShar.setVisibility(View.GONE);
        presenter.getReadNumb(mode.id);
    }

    @OnClick(R.id.textR)
    public void onViewClicked() {
        WordActivity.open(getActivity(), mode.documentPath);
    }

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            switch (buttonView.getId()) {
                case R.id.radio1:
                    isChecked = TitleUtils.canEmail(mode.categoryID);
                    if (isChecked) floatBtn.setVisibility(View.VISIBLE);
                    //ViewHelper.setAlpha(floatBtn, 1);
                    textShar.setVisibility(View.VISIBLE);
                    switchFragment(fragments[0]);
                    break;
                case R.id.radio2:
                    floatBtn.setVisibility(View.INVISIBLE);
                    //ViewHelper.setAlpha(floatBtn, 0);
                    textShar.setVisibility(View.GONE);
                    switchFragment(fragments[1]);
                    break;
            }
        }
    }

    public void switchFragment(BaseFragment fragment) {
        if (fragment == oldFragment) return;
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (!fragment.isAdded()) {
            transaction.add(R.id.layoutFrame, fragment, fragment.getClass().getName());
        } else {
            transaction.show(fragment);
            fragment.onResume();
        }
        if (oldFragment != null) {
            transaction.hide(oldFragment);
        }
        oldFragment = fragment;
        transaction.commitAllowingStateLoss();
    }

    public void getAttenRet(AttenMode data) {
        if (data == null) return;
        attenMode = data;
        if (oldFragment != null) {
            oldFragment.sendMessage(1, attenMode);
        }
    }

    public void sendAttenRet(int atten) {
        if (attenMode == null) attenMode = new AttenMode();
        attenMode.isAttention = atten;
        if (oldFragment != null) {
            oldFragment.sendMessage(1, attenMode);
        }
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcastSync(new Intent(ActionAttenRef));
    }

    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
        handler.removeCallbacksAndMessages(null);
        handler = null;
        isRun = false;
    }

    public void getDetailsModeRet(ListMsgMode data) {
        mode = data;
        if (oldFragment != null) {
            oldFragment.sendMessage(1, data);
        }
    }

    public void getReadNumbRet(Integer data) {
        if (fragments[0] != null) {
            fragments[0].sendMessage(4, data.intValue() + "");
        }
    }

    @OnClick(R.id.textShar)
    public void onTextSharClicked() {
        Resources res = getResources();
        Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.ic_app_launcher);
        MoreAreaShareMenu shareMenu = new MoreAreaShareMenu(getActivity());
        String url = mode.htmlPath;
        if (TextUtils.isEmpty(url)) {
            String imagePath = mode.imagePath;
            if (!TextUtils.isEmpty(imagePath)) {
                String[] split = imagePath.split(",");
                url = split[0];
            }
            if (!url.contains("://")) {
                url = BaseService.ImgURL + url;
            }
        }
        //imagePath.split("");
        shareMenu.setData(res.getString(R.string.app_name), url, bitmap
                , new ArrayList<String>(), mode.title);
        shareMenu.showPopupWindow(layoutTitle);
    }

    @OnClick(R.id.floatBtn)
    public void onFloatBtnClicked() {
        if (!isLogin()) return;
        PublicDialog dialog = new PublicDialog(getActivity())
                .setTitle(null).setContent("确认将该页面内容发送到您绑定的邮箱吗")
                .setOnPublicDialogClick(new PublicDialog.OnPublicDialogClick() {
                    public void onConfirmClick() {
                        if (isLogin()) presenter.sendEmail(mode.id);
                    }

                    public void onCancelClick() {
                    }
                });
        dialog.show();
    }

    public void sendEmailSucc() {
        ShowToast.alertShortOfWhite(getActivity(), R.string.fasongchenggong);
    }
}
